package com.fadadianqi.commons;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.Properties;

public class ConfigHelper {

    private static final Log log = LogFactory.getLog(ConfigHelper.class);

    private static Properties prop = new Properties();

    private static long lasttime = 0;

    private static BufferedReader in;

    private static File file;

    static {
        file = new GetConfigFile("config.properties").get();
        if (file != null && (lasttime == 0 || file.lastModified() > lasttime)) {
            try {
                in = new BufferedReader(
                        new InputStreamReader(
                                new FileInputStream(file), Constants.DEFAULT_CHARSET));
                prop.load(in);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void set(String key, String val) {
        prop.setProperty(key, val);
        try {
            prop.store(new FileOutputStream(file), null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error(e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
        }
    }

    public static void del(String key) {
        prop.remove(key);
    }

    public static String getString(String key) {
        return prop.getProperty(key);
    }

    public static String getString(String key, String def) {
        String value = getString(key);
        if (value == null) {
            return def;
        }
        return value;
    }

    public static int getInt(String key, int i) {
        try {
            return new Integer(prop.getProperty(key));
        } catch (Exception e) {
            log.error("key: " + key + ", i: " + i + ", value: " + prop.getProperty(key));
            e.printStackTrace();
        }
        return i;
    }

    public static Boolean getBoolean(String key) {
        try {
            return new Boolean(prop.getProperty(key, "false"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Boolean.FALSE;
    }
}
